package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entity.Student;
import entity.Teacher;
import service.StudentService;
import service.TeacherService;



/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private TeacherService teacherService=new TeacherService();
	private StudentService studentService=new StudentService();
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String username=request.getParameter("username");
		String password=request.getParameter("pwd");
		Teacher teacher=teacherService.findByUsernameAndPassword(username, password);
		if(teacher==null) {	
			Student student=studentService.findByStuNoAndPassword(username, password);
			if(student==null) {
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}else {
				session.setAttribute("user", student);
				request.getRequestDispatcher("jsp/stuMain.jsp").forward(request, response);				
			}
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}else {
			session.setAttribute("user",teacher );
			request.getRequestDispatcher("jsp/main.jsp").forward(request, response);			
		}
			
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
